import {
  AudioSource,
  AudioClip,
  _decorator,
  Collider2D,
  Component,
  Contact2DType,
  v3,
  Node,
  UITransform,
  resources,
  type EventTouch,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("plane")
export class plane extends Component {
  targetNode: Node | null = null;
  parentNode: Node | null = null;
  _audioSource: AudioSource = null;
  clipList: AudioClip[] = [];
  _index: number = 0;
  onLoad() {
    const audioSource = this.node.getComponent(AudioSource)!;
    resources.load(["mp3/papa", "mp3/dong"], AudioClip, (err, data) => {
      console.log("err", err);
      console.log("data", data);
      this.clipList = data;
      this._audioSource = audioSource;
      this._audioSource.clip = this.clipList[this._index];
      audioSource.node.on(AudioSource.EventType.ENDED, this.onAudioEnded, this);
    });
  }
  onAudioEnded() {
    this._index++;
    if (this._index > 1) {
      this._index = 0;
      this._audioSource.clip = this.clipList[this._index];
      return;
    }
    this._audioSource.clip = this.clipList[this._index];
    this._audioSource.play();
  }
  start() {
    const collider = this.node.getComponent(Collider2D);
    this.parentNode = this.node.getParent();
    if (collider) {
      collider.on(Contact2DType.BEGIN_CONTACT, this.onBeginContact, this);
      collider.on(Contact2DType.END_CONTACT, this.onEndContact, this);
    }
    this.node.on(Node.EventType.TOUCH_START, this.onTouchStart, this);
    this.node.on(Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
    this.node.on(Node.EventType.TOUCH_END, this.onTouchEnd, this);
  }
  onTouchStart() {
    this.node.parent.setSiblingIndex(10);
    this._audioSource.play();
  }
  onTouchMove(e: EventTouch) {
    const p = e.getLocation();
    const ui = this.node.parent.getComponent(UITransform);
    const pLocal = ui.convertToNodeSpaceAR(v3(p.x, p.y, 0));
    this.node.setPosition(pLocal);
  }
  onTouchEnd(e: EventTouch) {
    this.node.parent.setSiblingIndex(0);
    if (!this.targetNode || this.targetNode == this.parentNode) {
      // this.node.setPosition(0, 0, 0);
      return;
    }
    this.parentNode = this.targetNode;
    this.node.setParent(this.targetNode);
    this.node.setPosition(0, 0, 0);
  }
  onBeginContact(self: Collider2D, other: Collider2D) {
    this.targetNode = other.node;
  }
  onEndContact(self, other) {
    this.targetNode = null;
  }

  update(deltaTime: number) {}
}
